<template>
  <div>
    <!-- 添加按钮 -->
    <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">Add</a-button>

    <!-- 删除选中项按钮 -->
    <a-button
      type="danger"
      style="margin-bottom: 8px"
      @click="deleteSelected"
      :disabled="!selectedRowKeys.length"
    >
      Delete Selected
    </a-button>

    <!-- 表格 -->
    <a-table
      row-key="id"
      bordered
      :data-source="dataSource"
      :columns="columns"
      :row-selection="rowSelection"
    >
      <template #bodyCell="{ column, text, record }">
        <!-- 可编辑单元格  && editableData[record.id][column.dataIndex]-->
        <template v-if="column.editable">
          <div class="editable-cell">
            <div v-if="editableData[record.id]" class="editable-cell-input-wrapper">
              <a-input
                v-model:value="editableData[record.id][column.dataIndex]"
                @pressEnter="save(record.id)"
              />
              <check-outlined class="editable-cell-icon-check" @click="save(record.id)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || ' ' }}
              <edit-outlined
                class="editable-cell-icon"
                @click="edit(record.id, column.dataIndex)"
              />
            </div>
          </div>
        </template>

        <!-- 查看和删除操作 -->
        <template v-else-if="column.dataIndex === 'operation'">
          <a-space size="middle">
            <a @click="viewDetails(record)">查看</a>
            <a-popconfirm title="Sure to delete?" @confirm="onDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
  
  <script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import type { Ref, UnwrapRef } from 'vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';
import { getAllUsers,update } from '@/api/user-api/userApi';
import { message } from 'ant-design-vue';
import type { DataItem } from "@/type/type";
// 用户数据类型定义
// interface DataItem {
//   id: number;
//   username: string;
//   userAccount: string;
//   avatarUrl: string;
//   gender: number;
//   userPassword: string;
//   phone: string;
//   email: string;
//   userStatus: string;
//   createTime: string;
//   updateTime: string;
//   isDelete: number;
//   userRole: number;
// }

// 列定义
const columns = ref([
  {
    title: 'ID',
    dataIndex: 'id',
    editable: false,
  },
  {
    title: '用户名',
    dataIndex: 'username',
    editable: true,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    editable: true,
  },
  // {
  //   title: 'Avatar URL',
  //   dataIndex: 'avatarUrl',
  //   editable: true,
  // },
  {
    title: '性别',
    dataIndex: 'gender',
    editable: true,
  },
  {
    title: '密码',
    dataIndex: 'userPassword',
    editable: true,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    editable: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
]);

// import { getAllUsers } from "@/api/user-api/userApi";

// 初始用户数据
const dataSource: Ref<DataItem[]> = ref([
  {
    id: 1,
    username: 'admin',
    userAccount: 'admin123',
    avatarUrl: 'https://example.com/avatar1.jpg',
    gender: 1,
    userPassword: 'adminpass',
    phone: '1234567890',
    email: '',
    userStatus: 0,
    createTime: '',
    updateTime: '',
    isDelete: 0,
    userRole: 1,
  },
]);

// import axios from 'axios';
// 获取数据并赋值
onMounted(async () => {
  try {
    // 将数据赋值给响应式引用
    dataSource.value = await getAllUsers();
  } catch (error) {
    console.error('Error fetching data:', error);
  }
});

// 其他数据和函数
const count = computed(() => dataSource.value.length + 1);
const editableData: UnwrapRef<Record<string, Partial<DataItem>>> = reactive({});

const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  selectedRowKeys,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys;
  },
};
//编辑单元格
const edit = (id: string, dataIndex: keyof DataItem) => {
  if (!editableData[id]) {
    editableData[id] = cloneDeep(dataSource.value.find(item => id === item.id) || {});
  }
  if (!editableData[id][dataIndex]) {
    editableData[id][dataIndex] = dataSource.value.find(item => id === item.id)?.[dataIndex];
  }
};
//保存更改
const save =async (id: string) => {
  Object.assign(
    dataSource.value.find(item => id === item.id),
    editableData[id],
  );
  const response = await update(editableData[id]);
  message.info(response);
  delete editableData[id];
};
//操作删除
const onDelete = (id: string) => {
  dataSource.value = dataSource.value.filter(item => item.id !== id);
  selectedRowKeys.value = selectedRowKeys.value.filter(k => k !== id);
};
//增加用户
const handleAdd = () => {
  const newData: DataItem = {
    id: `${count.value}`,
    username: `user${count.value}`,
    userAccount: `userAccount${count.value}`,
    avatarUrl: `https://example.com/avatar${count.value}.jpg`,
    gender: `unknown`,
    userPassword: `password${count.value}`,
    phone: `0000000000`,
  };
  dataSource.value.push(newData);
};
//删除用户
const deleteSelected = () => {
  console.log(selectedRowKeys.value);
  dataSource.value = dataSource.value.filter(item => !selectedRowKeys.value.includes(item.id));
  selectedRowKeys.value = [];
};
//跳转详情页
import { useRouter } from 'vue-router';
import Detail from '@/views/Detail.vue'
const router = useRouter();
const viewDetails = (record: DataItem) => {
  // console.log(router);
  
  // router.addRoute({path:'/detail',component:Detail})
  // router.replace(router.currentRoute.value.fullPath)
  // console.log(router);

  const url = router.resolve({
    name: 'detail',
    query: { param: record.userAccount },
  }).href;
  console.log(url);
  window.open(url, '_blank');
};
</script>
  
  <style lang="less" scoped>
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
  